import React, { FC, useState, useEffect } from "react"
import { useNavigate } from "react-router-dom"
import { Layout, Menu } from "antd"
import { menuData } from "./KnowledgeSiderMenuConfig"
import { useLocation } from "react-router-dom"

const { Sider } = Layout

const KnowledgeSider: FC = () => {
  const nav = useNavigate()
  const location = useLocation()

  const [MyOpenKyes, SetMyOpenKyes] = useState<string[]>([])

  useEffect(() => {
    const pathSegments = location.pathname.split("/")

    // 找到包含 "knowledge" 的段
    const knowledgeIndex = pathSegments.findIndex(
      (segment) => segment === "knowledge"
    )

    if (
      MyOpenKyes.length === 0 &&
      knowledgeIndex !== -1 &&
      pathSegments.length > knowledgeIndex + 1
    ) {
      // 获取 "knowledge" 之后的段作为 menuKey
      const menuKeyToOpen = pathSegments[knowledgeIndex + 1]

      SetMyOpenKyes([menuKeyToOpen]) // 注意这里需要数组
    }
  }, [location])

  const handleClick = (e: any) => {
    nav(`/knowledge/${e.keyPath.reverse().join("/")}`)
  }

  return (
    <>
      <Sider width={200} style={{ background: "#fff" }}>
        <Menu
          mode="inline"
          openKeys={MyOpenKyes}
          defaultSelectedKeys={[""]}
          style={{ height: "100%" }}
          items={menuData}
          onClick={handleClick}
          onOpenChange={(keys) => SetMyOpenKyes(keys)}
        />
      </Sider>
    </>
  )
}

export default KnowledgeSider
